package com.zj;

import java.util.ArrayList;
import java.util.List;

/**
 * 银行类  ===>账户集合==>多线程操作的资源  ==>对象锁
 */
public class Bank {
    private List<BankAccount> accounts=new ArrayList<>();

    public Bank(){
        //初始化10个账户
        for (int i = 0; i < 10; i++) {
            accounts.add(new BankAccount(i,10));
        }
    }

    //查询：无需加锁
    public BankAccount search(int id) throws Exception {
        for (BankAccount account : accounts) {
            if(account.getId()==id){
                return account;
            }
        }
        throw new Exception("账号不存在");
    }

    //存款
    public BankAccount deposit(int id,double money) throws Exception {
        BankAccount account=search(id);     //查询不加锁
        synchronized (account){  //锁 粒度细化   插入操作修改加锁
            account.setBalance(account.getBalance()+money);
        }
        return account;
    }

    //取款
    public BankAccount withdraw(int id,double money) throws Exception {
        BankAccount account=search(id);
        synchronized (account){
            if(account.getBalance()<money){
                throw new Exception("余额不足");
            }
            account.setBalance(account.getBalance()-money);
        }
        return account;
    }
}
